from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from django.views.generic.base import View

from system.models import UserProfile
from rbac.custom import BreadcrumbMixin
from rbac.mixin import LoginRequiredMixin
from rbac.models import Structure
from .forms import StructureForm


class StructureView(LoginRequiredMixin, BreadcrumbMixin, TemplateView):
    """组织架构页面"""

    template_name = 'system/structure/structure.html'


class StructureCreateView(LoginRequiredMixin, View):
    """添加组织架构"""

    def get(self, request):
        ret = dict(structure_all=Structure.objects.all())

        if request.GET.get('id'):
            structure = get_object_or_404(Structure, pk=request.GET.get('id'))
            ret['structure'] = structure
        return render(request, 'system/structure/structure_create.html', ret)

    def post(self, request):
        ret = dict(result=False)
        if request.POST.get('id'):
            structure = get_object_or_404(Structure, pk=request.POST.get('id'))
        else:
            # 若不存在，则使用空模型
            structure = Structure()
        structure_form = StructureForm(request.POST, instance=structure)
        if structure_form.is_valid():
            structure_form.save()
            ret['result'] = True

        return JsonResponse(ret)


class StructureListView(LoginRequiredMixin, View):
    """组织架构列表"""

    def get(self, request):
        fields = ['id', 'name', 'type', 'parent__name']
        ret = dict(data=list(Structure.objects.values(*fields)))

        return JsonResponse(ret)


class StructureDeleteView(LoginRequiredMixin, View):
    """组织结构删除"""

    def post(self, request):
        ret = dict(result=False)
        if request.POST.get('id'):
            id_list = map(int, request.POST.get('id').split(','))
            Structure.objects.filter(id__in=id_list).delete()
            ret['result'] = True

        return JsonResponse(ret)


class Structure2UserView(LoginRequiredMixin, View):
    """组织架构关联用户"""

    def get(self, request):
        ret = dict()
        id = request.GET.get('id', None)
        if id:
            structure = get_object_or_404(Structure, pk=int(id))
            added_users = structure.userinfo_set.all()  # 所有已绑定该组织架构的用户信息
            all_users = UserProfile.objects.all()  # 所有用户信息
            # 计算差集，得出未绑定该组织的用户，将数据返回前端，左侧为未绑定的用户，右侧为已绑定的用户
            un_add_users = set(all_users).difference(added_users)
            ret = dict(structure=structure, added_users=added_users, un_add_users=list(un_add_users))

        print(ret)
        return render(request, 'system/structure/structure_user.html', ret)

    def post(self, request):
        res = dict(result=False)
        id_list = None
        structure = get_object_or_404(Structure, pk=int(request.POST.get('id')))

        # 获取需要绑定到 structure 实例的用户 id
        to = request.POST.get('to', [])
        if to:
            id_list = map(int, to)

        # 清空组织架构原有用户绑定的信息
        structure.userinfo_set.clear()
        if id_list:
            # 绑定新的用户数据
            for user in UserProfile.objects.filter(id__in=id_list):
                structure.userinfo_set.add(user)
        res['result'] = True

        return JsonResponse(res)

